package com.example.customException;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;


@Order(-1000)//首先加载异常处理
public class ExceptionResolver implements HandlerExceptionResolver {
    private static Logger logger= LoggerFactory.getLogger(ExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        ResultVO result= new ResultVO();
        StringBuilder sb= new StringBuilder();
        if(e instanceof BussinessException){
            resolverBussinessException(e,sb,result);
        }else if(e instanceof BindException){
            resolverBindException(e,sb,result);
        }else {
            resolverOtherException(e,sb,result);
        }
        result.setCode(0);
        result.setResult(sb);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache,must-revalidate");
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        logger.debug("异常："+e.getMessage(),e);
        e.printStackTrace();
        return new ModelAndView();
    }

    private void resolverBindException(Exception ex,StringBuilder sb,ResultVO result){
        BindException bindException= (BindException) ex;
        List<FieldError> errors= bindException.getBindingResult().getFieldErrors();
        for(FieldError error:errors){
            sb.append(error.getObjectName());
            sb.append("对象的：");
            sb.append(error.getField());
            sb.append("字段");
            sb.append(error.getDefaultMessage());
        }
        addResult(result,"参数传递异常。");
    }

    private void resolverBussinessException(Exception ex,StringBuilder sb,ResultVO result){
        BussinessException bussinessException= (BussinessException) ex;
        sb.append(bussinessException.getMessage());
        addResult(result,"业务异常。");

    }

    private void resolverOtherException(Exception ex,StringBuilder sb,ResultVO result){
        sb.append(ex.getMessage());
        addResult(result,"其它异常。");
    }

    private void addResult(ResultVO resultVO,String msg){
        resultVO.setMessage(msg);
    }
}
